import 'dart:async';
import 'dart:ui';

import 'package:factoryside/bean/addr_entity.dart';
import 'package:factoryside/service/order_service.dart';
import 'package:factoryside/utils/ColorsUtils.dart';
import 'package:factoryside/utils/utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'page_address.dart';

///收件地址列表页面

class AddrListPage extends StatefulWidget {

  AddrListPage();

  @override
  _AddrListPageState createState() => _AddrListPageState();
}

class _AddrListPageState extends State<AddrListPage>
    with AutomaticKeepAliveClientMixin {
  var items = new List<AddrData>();
  RefreshController _refreshController =
  RefreshController(initialRefresh: false);

  @override
  void initState() {
    super.initState();
    _fetchData();
  }

  void _fetchData() {
    OrderService.getAccountAddress().then((value) => this.setState(() {
      items=value.data;
    }));
  }

  @override
  void dispose() {
    print('dispose');
    _refreshController.dispose();
    super.dispose();
  }

  void _onRefresh() async {
    await Future.delayed(Duration(milliseconds: 1000));

    _fetchData();
    _refreshController.resetNoData();
    _refreshController.refreshCompleted();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context); //必须实现 不然 在push过后页面会刷新
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: buildAppBar('收件地址', [
          IconButton(icon: Icon(Icons.add,color: Colors.black,), onPressed: () async {
            var result=await Navigator.push(this.context,
                CupertinoPageRoute(builder: (BuildContext context) {
                  return AddressPage(null);
                }));
            if(result!=null){
              _fetchData();
            }
          })
        ], context),
        body: Container(
    color: ColorsUtil.hexToColor('#F2F2F2'),
    child: items.length==0?buildSmartRefresher(buildEmptyContainer()):buildSmartRefresher(ListView.builder(
    itemBuilder: (context,i){
      return buildItem(items[i]);
    },
    itemCount: items.length,
    )),
    ));

  }

  Container buildEmptyContainer() {
    return Container(
      color: Colors.white,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              'assets/v3_nodata.png',
              width: 100,
              height: 100,
            ),
            Text(
              '暂无地址',
              style: TextStyle(color: Colors.grey),
            ),
          ],
        ),
      ),
    );
  }

  Widget buildItem(AddrData data){
    return Container(
      color: Colors.white,
      margin: EdgeInsets.only(bottom: 10),
      padding: EdgeInsets.all(10),
      child: Row(
        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Visibility(
                        visible: data.isDefault=='1',
                        child: Row(
                          children: [
                            Container(
                              padding: EdgeInsets.symmetric(horizontal: 3),
                                decoration: BoxDecoration(
                                    color: Colors.blue,
                                    borderRadius: BorderRadius.all(Radius.circular(5))),
                                child: Text('默认',style: TextStyle(color: Colors.white,fontSize: 12),)),
                            SizedBox(width: 10),
                          ],
                        )),
                    Text(data.userName,style: TextStyle(fontWeight: FontWeight.bold)),
                    SizedBox(width: 20),
                    Text(data.phone)
                  ],
                ),
                Text('${data.province}${data.city}${data.area}${data.district}${data.address}',style: TextStyle(color: Colors.grey))
              ],
            ),
          ),
//          IconButton(icon: Icon(Icons.delete,size: 15,), onPressed: (){
//            showDialog<Null>(
//              context: context,
//              barrierDismissible: false,
//              builder: (context) {
//                return StatefulBuilder(builder: (context, state) {
//                  return AlertDialog(
//                    title: Center(
//                      child: Text('是否确认删除？'),
//                    ),
//                    actions: <Widget>[
//                      FlatButton(
//                        child: Text('取消'),
//                        onPressed: () {
//                          Navigator.of(context).pop();
//                        },
//                      ),
//                      FlatButton(
//                        child: Text('确定'),
//                        onPressed: () {
//                          RequestUtil.post(Api.deleteAccountAddress,
//                          {'AccountAdressID':data.accountAdressID}
//                          ).then((value){
//                            if(value['Data']['Item1']){
//                              _fetchData();
//                              Navigator.of(context).pop();
//                            }else{
//                              showToast(value['Data']['Item2']);
//                              Navigator.of(context).pop();
//                            }
//                          });
//                        },
//                      ),
//                    ],
//                  );
//                });
//              },
//            );
//          }),
          IconButton(icon: Image.asset('assets/bianji-copy.png',width: 15,height: 15,), onPressed: () async {
              var result=await Navigator.push(this.context,
                CupertinoPageRoute(builder: (BuildContext context) {
                  return AddressPage(data);
                }));
              if(result!=null){
                _fetchData();
              }
          }),
        ],
      ),
    );
  }

  SmartRefresher buildSmartRefresher(Widget child) {
    return SmartRefresher(
      enablePullDown: true,
      enablePullUp: false,
      controller: _refreshController,
      onRefresh: _onRefresh,
      child: child,
    );
  }

  @override
  bool get wantKeepAlive => true;
}
